//
//  UrbanWhereViewController.m
//  UrbanManagement
//
//  Created by Can on 18/4/11.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "UrbanWhereViewController.h"

@interface UrbanWhereViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,UITextFieldDelegate,BMKGeoCodeSearchDelegate,BMKRouteSearchDelegate>
@property (nonatomic, strong) BMKMapView *mapView;//地图
@property (nonatomic, strong) BMKPointAnnotation *annotationPoint;//大头针
@property (nonatomic, strong) BMKLocationService *locationManager;
@property (nonatomic, assign) double Mylatitude;///纬度
@property (nonatomic, assign) double Mylongitude;///经度
@property (nonatomic, strong) BMKGeoCodeSearch *searcher;//查询
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *whereLable;
@property (nonatomic, strong) NSString *cityStr;//城市
@property (nonatomic, strong) NSString *detailStr;//详细地址
@property (nonatomic, strong) BMKRouteSearch *routeSearch;

@end

@implementation UrbanWhereViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.mapView];

    [self.locationManager startUserLocationService];

    if (_mapType == 1) {
        [self creatNav];
        _locationManager.delegate = self;
    }else{
        CLLocationCoordinate2D customloc2D = CLLocationCoordinate2DMake([_latitude floatValue], [_longitude floatValue]);
        if (!_annotationPoint) {
            _annotationPoint = [[BMKPointAnnotation alloc] init];
        }
        _annotationPoint.coordinate = customloc2D;

        [self.mapView addAnnotation:_annotationPoint];
        self.mapView.centerCoordinate = customloc2D;
        [self addSearch:customloc2D];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self initTitleWithTitle:@"违法位置"];
    
    //是否开启GPS
    if (![TomamaUI isEnabledLocationServices]) {
        [TomamaUI openGPS];
    }
}

//不使用时将delegate设置为 nil
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _mapView.delegate = nil;
    _searcher.delegate = nil;
    _locationManager.delegate = nil;
}

- (void)creatNav
{
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn addTarget:self action:@selector(okBtn) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"确定" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [rightBtn sizeToFit];
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    self.navigationItem.rightBarButtonItem = rightBtnItem;
}

-(BMKMapView *)mapView
{
    if (!_mapView)
    {
        _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
        _mapView.delegate = self;
        _mapView.zoomLevel = 15;
        [_mapView setMapType:BMKMapTypeStandard]; //切换为标准地图
        _mapView.showsUserLocation = YES;//显示定位图层
        _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态为普通定位模式
        
    }
    return _mapView;
}

//定位
- (BMKLocationService *)locationManager
{
    if (!_locationManager)
    {
        _locationManager = [[BMKLocationService alloc] init];
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    }
    return _locationManager;
}

//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    if (!_annotationPoint) {
        _annotationPoint = [[BMKPointAnnotation alloc] init];
    }
    _annotationPoint.coordinate = userLocation.location.coordinate;
    //地图显示位置
    [self.mapView addAnnotation:_annotationPoint];
    self.mapView.centerCoordinate = userLocation.location.coordinate;
    [self addSearch:userLocation.location.coordinate];
    [_locationManager stopUserLocationService];//停止定位
}

- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate
{
    if (_mapType == 1) {
        //点击的某点在地图控件中的位置
        if (!_annotationPoint) {
            _annotationPoint = [[BMKPointAnnotation alloc] init];
        }
        _annotationPoint.coordinate = coordinate;
        
        [self.mapView addAnnotation:_annotationPoint];
        self.mapView.centerCoordinate = coordinate;
        
        [self addSearch:coordinate];
    }
}

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    if (_mapType == 1) {
        _annotationPoint.coordinate = mapView.centerCoordinate;
        
        [self addSearch:mapView.centerCoordinate];
    }
}

-(void)addSearch:(CLLocationCoordinate2D)pt{
    _searcher =[[BMKGeoCodeSearch alloc]init];
    _searcher.delegate = self;
    //发起反向地理编码检索
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];

    if(flag)
    {
        _latitude = [NSString stringWithFormat:@"%f",pt.latitude];
        _longitude = [NSString stringWithFormat:@"%f",pt.longitude];
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == BMK_SEARCH_NO_ERROR) {
//        NSLog(@"result:%@",result.poiList);
//        NSLog(@"result:%@",[result.poiList[0] address]);
       
        NSString *str = [NSString stringWithFormat:@"违法地点:%@",result.address];
        _whereLable.attributedText = [self textLable:str];
        _whereLable.frame = CGRectMake(15*screenW_6, 19*screenW_6, 458/2*screenW_6 - 30*screenW_6, [self lableHeight:_whereLable width:458/2*screenW_6 - 30*screenW_6]);
        
        _imageView.frame = CGRectMake(87/4*screenW_6 - 458/4*screenW_6, -(CGRectGetMaxY(_whereLable.frame) + 38*screenW_6), 458/2*screenW_6, CGRectGetMaxY(_whereLable.frame) + 38*screenW_6);
        
        _detailStr = result.address;
        _cityStr = [result.poiList[0] city];
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    static NSString *whereReuseIndetifier =@"whereReuseIndetifier";
    BMKAnnotationView *annotationView = (BMKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:whereReuseIndetifier];
    
    if (annotationView ==nil)
    {
        annotationView = [[BMKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:whereReuseIndetifier];
        
        annotationView.canShowCallout =NO;
        annotationView.draggable =YES;
        annotationView.calloutOffset =CGPointMake(0, -5);
    }
    
    annotationView.image = [UIImage imageNamed:@"icon01"];
    
    [annotationView addSubview:[self imageV]];

    return annotationView;
}

//自定义大头针显示样式
- (UIImageView *)imageV
{
    _imageView = [TomamaUI createImageView:CGRectMake(-458/4*screenW_6, 0, 458/2*screenW_6, 178/2*screenW_6) backGroundImageV:@"mapbg"];
    
    _whereLable = [[UILabel alloc]initWithFrame:CGRectMake(15*screenW_6, 19*screenW_6, 458/2*screenW_6 - 30*screenW_6, 30)];
    
    _whereLable.textAlignment = NSTextAlignmentLeft;
    
    _whereLable.font = [UIFont systemFontOfSize:13*screenW_6];
    
    _whereLable.textColor = Color(51, 51, 51);
    
    _whereLable.attributedText = [self textLable:@"违法地点:"];
    
    [_imageView addSubview:_whereLable];
    
    _whereLable.frame = CGRectMake(15*screenW_6, 19*screenW_6, 458/2*screenW_6 - 30*screenW_6, [self lableHeight:_whereLable width:458/2*screenW_6 - 30*screenW_6]);
    
    _imageView.frame = CGRectMake(87/4*screenW_6 - 458/4*screenW_6, -(CGRectGetMaxY(_whereLable.frame) + 38*screenW_6), 458/2*screenW_6, CGRectGetMaxY(_whereLable.frame) + 38*screenW_6);
    
    return _imageView;
}

//富文本改变字体颜色
- (NSMutableAttributedString *)textLable:(NSString *)string
{
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:string];
    [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:Color(242, 48, 48)
     
                          range:NSMakeRange(0, 5)];
    return AttributedStr;
}

//lable高度计算
- (CGFloat)lableHeight:(UILabel *)lable width:(CGFloat)width{
    lable.numberOfLines = 0;//根据最大行数需求来设置
    lable.lineBreakMode = NSLineBreakByTruncatingTail;
    CGSize maximumLabelSize = CGSizeMake(width, 9999);//labelsize的最大值
    //关键语句
    CGSize expectSize = [lable sizeThatFits:maximumLabelSize];
    return expectSize.height;
}

//回调选中的地址
- (void)okBtn
{
    if (_UrbanWhereViewControllerBlock) {
        _UrbanWhereViewControllerBlock(_cityStr,_detailStr,_latitude,_longitude);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
